<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>可中断更新</title>
  <style>
    #container {
      word-break: break-all;
    }

    @keyframes blink {
      from,
      to {
        border-color: transparent;
      }

      50% {
        border-color: white;
      }
    }
  </style>
</head>
<body>
<button id="push">插队任务</button>
<button id="start">执行</button>

<div id="container"></div>

<script>
const container = document.getElementById('container')
const btn = document.getElementById('start')
const pushBtn = document.getElementById('push')
function task() {
  const startTime = performance.now()
  let span = document.createElement('span')
  span.innerText = 1

  while (performance.now() - startTime < 5) {
    // 阻塞 1 ms
  }
  container.appendChild(span)
}

const taskQueue = Array.from({ length: 1000 }, () => task)

function performWorkUnit() {
  if (taskQueue.length === 0) {
    btn.innerText = '执行'
    return
  }

  requestIdleCallback(deadline => {
    let task;
    while ((task = taskQueue.pop()) && !deadline.didTimeout && deadline.timeRemaining() > 0) {
      task()
    }
    performWorkUnit()
  })
}

btn.onclick = () => {
  btn.innerText = '已点击，插入中'

  requestIdleCallback(performWorkUnit)
}

function highPriorityTask() {
  const startTime = performance.now()
  let span = document.createElement('span')
  span.style.color = 'red'
  span.innerHTML = '<strong>插队任务</strong>'

  while (performance.now() - startTime < 1) {
    // 阻塞 1 ms
  }
  container.appendChild(span)
}

pushBtn.onclick = function () {
  taskQueue.push(highPriorityTask)
}

</script>
</body>
</html>